package cmd

import (
	"fmt"
	"go-stage/core"
	pb "go-stage/micro/pb"
	os_server "go-stage/micro/system/server"
	user_server "go-stage/micro/user/server"
	"go-stage/ws"

	"github.com/spf13/cobra"
	"github.com/spf13/viper"
	"google.golang.org/grpc"
)

var serverCmd = &cobra.Command{
	Use:   "server",
	Short: "run server",
	Long:  "run server",
	Run: func(cmd *cobra.Command, args []string) {
		var v *viper.Viper
		var err error
		if v, err = core.ReadConfig(config, "toml", "userws"); err != nil {
			fmt.Printf("read config error: %v\n", err)
			return
		}
		if err = core.InitLogger(v); err != nil {
			fmt.Printf("logger config error: %v", err)
			return
		}
		if err = core.InitDB(v); err != nil {
			core.Log.Errorf("mysql config error: %v", err)
			return
		}
		if err = core.InitRedis(v); err != nil {
			core.Log.Errorf("redis config error: %v", err)
			return
		}

		var registerServices []func(s *grpc.Server)
		switch name {
		case "userws":
			registerServices = userws()
		case "osws":
			registerServices = osws()
		}

		w := ws.Ws{Address: address, RegisterServiceFuncs: registerServices}
		w.Run()
	},
}

var (
	config  string // 配置文件路径
	address string // 服务访问地址 (127.0.0.1:8080)
	name    string // 服务名称
)

func init() {
	serverCmd.Flags().StringVarP(&config, "config", "c", "", "config file path")
	serverCmd.Flags().StringVarP(&address, "address", "a", "", "server address (127.0.0.1:8080)")
	serverCmd.Flags().StringVarP(&name, "name", "n", "", "server name")
}

func userws() []func(s *grpc.Server) {
	registerServices := make([]func(s *grpc.Server), 0)
	registerServices = append(registerServices, func(s *grpc.Server) {
		pb.RegisterUserServiceServer(s, user_server.UserService)
	})
	return registerServices
}

func osws() []func(s *grpc.Server) {
	registerServices := make([]func(s *grpc.Server), 0)
	registerServices = append(registerServices, func(s *grpc.Server) {
		pb.RegisterDictServiceServer(s, os_server.DictService)
	})
	return registerServices
}
